//#########################################################################
//                              WackiEngie
//           Copyright (c) 2014 Marc Wacker. All rights reserved.
//#########################################################################

#include "WeDebug.h"
#include "WeTime.h"


#define SECONDSTOMINS  1.0/60.0
#define SECONDSTOHOURS 1.0/(60.0*60.0)

namespace WackiEngine
{

	Debug::Debug()
	{
		// connect to print out new entries in console
		_log.entryAdded.connect(this, &Debug::printLogEntry);
	}

	void Debug::log(const String& msg, const String& channel, const String& file, uint32 line)
	{
		_log.addEntry(msg, channel, file, line);
	}

	// use this function to output to debug console, dont use cout, printf or other
	void Debug::printConsole(const String& msg)
	{
		std::cout << msg;
	}


	void Debug::printLogEntry(const LogEntry& entry)
	{
		// format time
		// TODO: put time formattnig somewhere else
		// TODO: only print msgs in non release builds
		double curTime = entry.getTime() + 200.0;
		int32 hours, mins, secs;

		hours = (int32)floor(curTime * SECONDSTOHOURS);
		curTime -= hours * 60 * 60;

		mins = (int32)floor(curTime * SECONDSTOMINS);
		curTime -= mins * 60;

		secs = (int32)floor(curTime);

		String time = toString(hours, 2, '0') + ":" + toString(mins, 2, '0') + ":" + toString(secs, 2, '0');

		//find file name
		const String& path = entry.getFile();
		String filename = String(std::find_if(path.rbegin(), path.rend(), [](char ch) { return ch == '/' || ch == '\\'; }).base(), path.end());

		//printConsole("[" + entry.getChannel() + "- " + time + "]: " + entry.getMsg() + " (" + filename + " : " + std::to_string(entry.getLine()) + ")\n");
		printConsole("[" + entry.getChannel() + "]: " + entry.getMsg() + " (" + filename + " : " + std::to_string(entry.getLine()) + ")\n"); // no time stamp here
	}

	// lazy singleton
	// TODO: would a Module be better here?
	Debug& gDebug()
	{
		static Debug instance;
		return instance;
	}

}